import type { FC } from 'react';
import { useState } from 'react';
import Loading from '../Loading';
import { useAsyncEffect, useMemoizedFn } from 'ahooks';

import styles from './styles.module.less';

type Loader = () => Promise<{ default: any }>;

interface ILoadComponentProps {
  loader: Loader;
}

const LoadComponent: FC<ILoadComponentProps> = (
  (props) => {
    const [Node, setNode] = useState<any>(null);

    const loadComponent = useMemoizedFn(async () => {
      const res = await props.loader();
      setNode(() => res.default);
    });

    // 加载组件
    useAsyncEffect(loadComponent, [loadComponent]);

    if (!Node) {
      return (
        <div className={styles.loading}>
          <Loading />
        </div>
      );
    }
    return <Node />;
  }
);

export default (loader: Loader) => <LoadComponent loader={loader} />;